package com.nnxy.controller;

import com.nnxy.pojo.PageResult;
import com.nnxy.pojo.Result;
import com.nnxy.pojo.Student;
import com.nnxy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/students")
@RestController
public class StudentController {
    @Autowired
    StudentService studentService;

    @GetMapping
    public Result page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10")  Integer pageSize,
            String name,
            Integer degree,
            Integer clazzId
    ){
        PageResult<Student> pageResult = studentService.findByPage(page, pageSize, name, degree, clazzId);
        return new Result(1,"success",pageResult);
    }


    @PostMapping
    public Result add(@RequestBody Student student) {
        try {
            studentService.add(student);
            return new Result(1, "success", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(0, "添加失败", null);
        }
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        Result res;
        try {
            studentService.deleteById(ids);
            res = new Result(1, "success", null);
        } catch (Exception e) {
            res = new Result(0,"fail",null);
        }
        return res;
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Student student = studentService.findById(id);
        return new Result(1, "success", student);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        try {
            studentService.update(student);
            return new Result(1, "success", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(0, "修改失败", null);
        }
    }
    @PutMapping("/violation/{id}/{score}")
    public Result handleViolation(
            @PathVariable Integer id,
            @PathVariable Integer score) {
        try {
            // 根据 ID 查询学生信息
            Student student = studentService.findById(id);
            if (student == null) {
                return new Result(0, "学生不存在", null);
            }

            // 更新违纪次数和违纪分数
            student.setViolationCount((short) (student.getViolationCount() + 1));
            student.setViolationScore((short) (student.getViolationScore() + score));

            // 调用业务层更新学生信息
            studentService.update(student);
            return new Result(1, "success", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(0, "error", null);
        }
    }
}
